/**
 * 园区分布地图
 */

function MapPark(container, settings){
	var defaultOptions = {
			path: '',
			type:null,
			parkid:null,
			size: 200,
			center: "河北",//{lng:lng, lat:lat, zoom:zoom}或字符串格式的位置名称
			boundary: null,//边界名（省、市或县的名称）
			getInfoWindow: null,//getInfoWindow(markerVo, callback(title, content))
			onMapStatus: null//地图状态
		};
	var g = this, p = jQuery.extend({}, defaultOptions, settings);;
	g._marks = new JSHashtable();
	g._datas = new JSHashtable();
	
	g._init = function(){
		g.markerNums = 0;
		g._initLoaded = false;
		g.map = new BMap.Map(container);
		g.map.enableScrollWheelZoom();
		g.map.enableContinuousZoom();
		g.map.addControl(new BMap.NavigationControl({type:BMAP_NAVIGATION_CONTROL_SMALL}));
		g.map.addControl(new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT}));
		g.map.addControl(new BMap.MapTypeControl({
			type:BMAP_MAPTYPE_CONTROL_HORIZONTAL, mapTypes:[BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP, BMAP_HYBRID_MAP]
		}));
		
		if(typeof p.center == "object"){
			g.map.centerAndZoom(new BMap.Point(p.center.lng, p.center.lat), p.center.zoom);
		}else{
			g.map.centerAndZoom(p.center);
		}
		
		//缩放事件
		g.map.addEventListener("zoomend", function(){
			g._load();
		});
		//平移事件
		g.map.addEventListener("moveend", function(){
			g._load();
		});
		
		//绘制边界
		if(p.boundary){
			g.bmapBoundary = new BMap.Boundary();
			g.bmapBoundary.get(p.boundary, function(rs){
				if(rs){
					var count = rs.boundaries.length;
					for(var i=0; i<count; i++){
			            var polygon = new BMap.Polygon(rs.boundaries[i], {strokeWeight:2, strokeColor:'#ff0000', fillColor:""});
			            g.map.addOverlay(polygon);
			        }
				}
		    });
		}
		
		g._infoWindow = new BMap.InfoWindow('', {offset:new BMap.Size(0, -12)});
		
		g._load();
	};
	
	g.setParkid = function(parkid){
		p.parkid = parkid;
	};
	
	g.centerAndZoom = function(center, zoom){
		g._initLoaded = false;
		if(typeof center == "object"){
			var zoom = parseInt(zoom)||parseInt(center.zoom)||12;
			g.map.centerAndZoom(new BMap.Point(center.lng, center.lat), zoom);
		}else{
			g.map.centerAndZoom(center);
		}
	};
	
	g._mapStatus = function(message){
		if(p.onMapStatus){
			var status = {center: g.map.getCenter(), zoom: g.map.getZoom(), markerNums: g.markerNums},
				bounds = g.map.getBounds(),
				southWest = bounds.getSouthWest(),
				northEast = bounds.getNorthEast();
			if(southWest && northEast){
				status.bounds = {E: northEast.lng, S: southWest.lat, W: southWest.lng, N: northEast.lat};
			}
			if(message){
				status.message = message;
			}
			p.onMapStatus.call(g, status);
		}
	};
	
	//获取标注图标
	g._getMarkerIcon = function(type, mini){
		return null;
	};
	
	g._load = function(){
		var center = g.map.getCenter(), zoom = g.map.getZoom();
		g._mapStatus();
		
		if(g._locked){
			return;
		}
		g._locked = true;
		g._token = '1'+String(Math.random()).substr(2);
		
		//地图边界
		var bounds = g.map.getBounds();
		var southWest = bounds.getSouthWest();//西南角
		var northEast = bounds.getNorthEast();//东北角
		if(!southWest){
			g._locked = false;
			return;
		}
		
		var param = [];
		param.push('token='+g._token);
		param.push('wlng='+southWest.lng);
		param.push('elng='+northEast.lng);
		param.push('nlat='+northEast.lat);
		param.push('slat='+southWest.lat);
		param.push('zoom='+zoom);
		param.push('size='+(p.size || 200));
		param.push('markerid='+(!p.marker ? '' : (p.marker.id || '')));
		param.push('type='+(p.type || ''));
		param.push('parkid='+(p.parkid || ''));
		
		jQuery.ajax({
			url:  p.path + '/parkmap/loadMapMarkers.json?'+ param.join("&"),
			type: 'GET',
			cache: false,
			dataType: 'json',
			success: function(data){
				if(typeof(data)=='string'){
					data = jQuery.parseJSON(data);
	    		}
				var token = data.token;
				if(token!=g._token){
					g._locked = false;
					return;
				}
				var list = data.list;//标注点列表
				if(list!=null && list.length>0){
					g.markerNums = list.length;
					var listMap = {};
					for(var i=0, len=list.length; i<len; i++){
						var mkrVo = list[i];
						listMap[mkrVo.id] = mkrVo;
					}
					//删除不显示的现有标注
					var keys = g._marks.getKeys();
					for(var i=0, len=keys.length; i<len; i++){
						var k=keys[i];
						if(typeof(listMap[k])=="undefined"||listMap[k]==null){
							g._deleteMarker(k);
						}
					}
					delete listMap;
					delete keys;
					//将新标注添加到地图
					for(var i=0, len=list.length; i<len; i++){
						var mkrVo = list[i];
						if(!g._marks.containsKey(mkrVo.id)){//如果地图上没有则添加
							var opt = {}, icon = g._getMarkerIcon(mkrVo.type);
							if(icon){
								opt.icon = icon;
							}
							var marker = new BMap.Marker(new BMap.Point(mkrVo.lng, mkrVo.lat), opt);
							marker.mid = mkrVo.id;
							marker.addEventListener("click", g._openInfoWindow);
							marker.setTitle(mkrVo.name);
							g.map.addOverlay(marker);
							g._marks.put(mkrVo.id, marker);
							g._datas.put(mkrVo.id, mkrVo);
						}
					}
				}else{
					g.markerNums = 0;
					g._deleteAll();
				}
				g._locked = false;
				g._mapStatus();
				
				if(!g._initLoaded){
					g._initLoaded = true;
					g.showInfoWindow(p.parkid);
				}
			},
			error:function(p1,p2,p3){
				g._locked = false;
				g._mapStatus('发生AJAX错误！'+p1+p2+p3);
			}
		});
		
	};
	
	//删除所有标注
	g._deleteAll=function(){
		var keys = g._marks.getKeys();
		for(var i=0, len=keys.length; i<len; i++){
			g._deleteMarker(keys[i]);
		}
	};
	
	//删除标注
	g._deleteMarker=function(mid){
		var marker = g._marks.get(mid);
		if(!marker){
			g._marks.remove(mid);
			g._datas.remove(mid);
			return;
		}
		var iw = g._infoWindow;
		if(iw.mkrid == marker.mid){
			if(iw instanceof BMap.InfoWindow){
				if(iw.isOpen()){
					marker.closeInfoWindow();
				}
			}else{
				iw.close();
			}
		}
		marker.removeEventListener("click", g._openInfoWindow);
		g.map.removeOverlay(marker);
		g._marks.remove(mid);
		g._datas.remove(mid);
	};
	
	//关闭信息窗口
	g.closeInfoWindow=function(){
		if(g._infoWindow){
			var iw = g._infoWindow;
			if(iw instanceof BMap.InfoWindow){
				if(iw.isOpen()){
					var _mkr = g._marks.get(iw.mkrid);
					if(_mkr){
						_mkr.closeInfoWindow();
					}
				}
			}else{
				iw.close();
			}
		}
	};
	
	//打开指定标注的信息窗口
	g.showInfoWindow=function(mid){
		var marker = g._marks.get(mid);
		if(marker){
			g._openInfoWindow(marker);
		}else{
			g.closeInfoWindow();
		}
	};
	
	//打开信息窗口
	g._openInfoWindow=function(evt){
		var marker = (evt instanceof BMap.Marker) ? evt : evt.target;
		if(g._infoWindow){
			var iw = g._infoWindow;
			if(iw instanceof BMap.InfoWindow){
				if(iw.isOpen()){
					var _mkr = g._marks.get(iw.mkrid);
					if(_mkr){
						_mkr.closeInfoWindow();
					}
				}
				iw.mkrid = marker.mid;
				var mkrVo = g._datas.get(marker.mid);
				if(typeof(p.getInfoWindow)=='function'){
					p.getInfoWindow.call(g, mkrVo, function(title, content){
						iw.setTitle('<span class="mkr_title">'+title+'</span>');
						if(content && content.indexOf('<') == -1){
							content = g.farmatContent(content);
						}
						iw.setContent(g.farmatContent(content) || title);
						iw.redraw();
						marker.openInfoWindow(iw);
					});
				}else{
					iw.setTitle('<span class="mkr_title">'+mkrVo.name+'</span>');
					var content = mkrVo.remark;
					if(content && content.indexOf('<') == -1){
						content = g.farmatContent(content);
					}
					iw.setContent(content || mkrVo.name);
					iw.redraw();
					marker.openInfoWindow(iw);
				}
			}else{//自定义消息框
				iw.close();
				iw.mkrid = marker.mid;
				var mkrVo = g._datas.get(marker.mid);
				if(typeof(p.getInfoWindow)=='function'){
					p.getInfoWindow.call(g, mkrVo, function(title, content){
						if(typeof iw.setTitle == 'function'){
							iw.setTitle('<span class="mkr_title">'+title+'</span>');
						}
						if(content && content.indexOf('<') == -1){
							content = g.farmatContent(content);
						}
						iw.setContent(content || '');
						iw.open(marker);
					});
				}else{
					if(typeof iw.setTitle == 'function'){
						iw.setTitle('<span class="mkr_title">'+mkrVo.name+'</span>');
					}
					var content = mkrVo.remark;
					if(content && content.indexOf('<') == -1){
						content = g.farmatContent(content);
					}
					if(!iw.setTitle){
						content = '<span class="mkr_title">'+mkrVo.name+'</span>'+content;
					}
					iw.setContent(content || '');
					iw.open(marker);
				}
			}
		}
	};
	
	//将内容用段落标签进行格式化
	g.farmatContent=function(content){
		if(content){
			content = content.replace(/&|>|<|"/g, function(){
				var c = arguments[0];
				switch(c){
				case '&': return '&amp;';
				case '>': return '&gt;';
				case '<': return '&lt;';
				case '"': return '&quot;';
				}
			});
			content = content.replace(/\r\n|\r|\n/g, '</p><p class="mkr_content">');
			content = '<p class="mkr_content">' + content +"</p>";
			content = content.replace('<p class="mkr_content"></p>', '');
		}
		return content;
	};
	
	g._init();
}

